<template>
  <div class="v-control v-select-container">
    <label v-text="props.label" v-if="props.label"></label>
    <el-select
        v-model="selectValue"
        :placeholder="defaultPlaceholder"
        :style="{ width: props.width + 'px' }"
        :disabled="props.disabled"
        :clearable="props.clearable"
        :filterable="props.filterable"
        :remote-method="remoteMethod"
        :remote="remote"
        :multiple="multiple"
        :remote-show-suffix="props.remoteShowSuffix"
        @clear="clear"
        :loading="props.loading"
        @blur="blur"
        @visible-change="visibleChange"
        @change="change"
    >
      <el-option
          v-for="item in props.selectOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
      />
    </el-select>
  </div>
</template>
<script lang="ts" setup>
import {ref, watch, onMounted, PropType} from 'vue'

const emits = defineEmits([
  'update:modelValue',
  'clear',
  'remoteMethod',
  'blur',
  'visibleChange',
  'change'])
const props = defineProps({
  modelValue: {
    type: String
  },
  selectOptions: {
    type: Array as PropType<{ value: string | number; label: string }[]>,
    default() {
      return []
    }
  },
  placeholder: {
    type: String,
    default: ''
  },
  width: {
    type: Number,
    default: 240
  },
  disabled: {
    type: Boolean,
    default: false
  },
  clearable: {
    type: Boolean,
    default: false
  },
  size: {
    type: String,
    default: 'large'
  },
  label: {
    type: String,
    default: ''
  },
  filterable: {
    type: Boolean,
    default: false
  },
  remote: {
    type: Boolean,
    default: false
  },
  remoteShowSuffix: {
    type: Boolean,
    default: false
  },
  multiple: {
    //是否多选
    type: Boolean,
    default: false
  },
  loading: {
    type: Boolean,
    default: false
  }
})

const selectValue = ref(props.modelValue)

watch(
    () => props.modelValue,
    () => {
      selectValue.value = props.modelValue
    }
)
watch(
    () => selectValue.value,
    () => {
      emits('update:modelValue', selectValue.value)
    }
)

const clear = () => {
  emits('clear')
}

const blur = () => {
  emits('blur')
}

const visibleChange = () => {
  emits('visibleChange')
}

const change = () => {
  emits('change')
}

const remoteMethod = (query: string) => {
  emits('remoteMethod', query)
}

let defaultPlaceholder = ref(props.placeholder)

onMounted(() => {
  if (props.placeholder === '' && props.label) {
    defaultPlaceholder.value = `请选择${props.label}`
  }
})
</script>
<style scoped lang="scss">
.v-select-container {
  margin-right: 15px;

  label {
    margin-right: 10px;
    font-size: $--el-font-size-base;
  }
}
</style>
